﻿using System.Drawing;
using System.Drawing.Imaging;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Provenance.Domain.Product;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Write.Api.Application.Command.Product;
using QRCoder;

namespace Provenance.Write.Api.Controllers
{
    [Route("api/writeprovenance/[controller]/[action]")]
    [ApiController]
    public class ProvenanceController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IProvenanceCodeRepository _provenanceCodeRepository;
        public ProvenanceController(IMediator mediator, IProvenanceCodeRepository provenanceCodeRepository)
        {
            _mediator = mediator;
            _provenanceCodeRepository = provenanceCodeRepository;
        }
        /// <summary>
        /// 导出随机码
        /// </summary>
        /// <param name="num"></param>
        /// <param name="ProductInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> ExportCode(int num,int ProductInfoId)
        {
            for(var i=0;i<num;i++)
            {
                Random random = new Random(); // 创建一个Random实例
                int randomNumber = random.Next(1, 10001);
                await _provenanceCodeRepository.InsertEntity(new ProvenanceCode()
                {
                    ProductInfoId = ProductInfoId,
                    ProvenanceCodeValue = randomNumber.ToString()
                });
            }
            IEnumerable<ProvenanceCode> provenanceCodes = await _provenanceCodeRepository.GetAllAsync();

            // 将集合中的每个ProvenanceCode对象转换为字符串，并使用逗号分隔它们
            string result = String.Join(", ", provenanceCodes.Select(code => code.ProvenanceCodeValue));
            var response=GetProvenanceCode(result, @"D:\所学课程\专高6练习\QRCodes");//返回地址 D:\所学课程\专高6练习\QRCodes\20241224212458.jpg
            //获取data[]数组和name


            return response; // 返回转换后的字符串
        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetProvenanceCode([FromQuery] string text="Hello World", string savePath= @"D:\所学课程\专高6练习\QRCodes")
        {
            try
            {
                // 创建 QR 码生成器实例
                QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrCodeGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.M, true);

                // 获取二维码图像的字节数组
                Color foregroundColor = Color.Black;
                Color backgroundColor = Color.White;

                // 将 Color 对象转换为 byte[] 数组
                byte[] foregroundColorBytes = new byte[]
                {
                   (byte)(foregroundColor.ToArgb() >> 24), // A
                   (byte)(foregroundColor.ToArgb() >> 16), // R
                   (byte)(foregroundColor.ToArgb() >> 8),  // G
                   (byte)(foregroundColor.ToArgb() & 0xFF)   // B
                };

                byte[] backgroundColorBytes = new byte[]
                {
                    (byte)(backgroundColor.ToArgb() >> 24), // A
                    (byte)(backgroundColor.ToArgb() >> 16), // R
                    (byte)(backgroundColor.ToArgb() >> 8),  // G
                    (byte)(backgroundColor.ToArgb() & 0xFF)   // B
                };

                // 使用 PngByteQRCode 生成二维码图像
                PngByteQRCode qrCode = new PngByteQRCode(qrCodeData);

                // 获取二维码图像的字节数组，使用转换后的 byte[] 颜色数组
                byte[] qrCodeBytes = qrCode.GetGraphic(15, foregroundColorBytes, backgroundColorBytes, false);


                // 将字节数组转换为 Bitmap 对象
                using (var ms = new MemoryStream(qrCodeBytes))
                using (var qrCodeImage = new Bitmap(ms))
                {
                    // 在图像上绘制文本
                    using (Graphics graphics = Graphics.FromImage(qrCodeImage))
                    {
                        Font font = new Font("Arial", 30, FontStyle.Bold);
                        graphics.DrawString(text, font, Brushes.Black, new PointF(10, 10));
                    }

                    // 保存图像
                    var imagePath = Path.Combine(savePath, $"{DateTime.Now:yyyyMMddHHmmss}.jpg");
                    qrCodeImage.Save(imagePath, ImageFormat.Jpeg);

                    return imagePath;
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并返回错误信息
                return ex.Message;
            }
        }
        [HttpPost]
        public async Task<ApiResult> InsertProductInfo(InsertProductInfoCommand param)
        {
            return await _mediator.Send(param);
        }
        [HttpDelete]
        public async Task<ApiResult> DelProductInfo(int ProductInfoId)
        {
            return await _mediator.Send(new DelProductInfoCommand()
            {
                ProductInfoId = ProductInfoId
            });
        }
        [HttpDelete]
        public async Task<ApiResult> DelRangeProductInfo(string ids)
        {
            return await _mediator.Send(new DelRangeProductInfoCommand()
            {
                ProductInfoIds = ids
            });
        }
        [HttpPut]
        public async Task<ApiResult> UpdateProductInfo(UpdateProductInfoCommand param)
        {
            return await _mediator.Send(param);
        }
        [HttpPost]
        public async Task<ApiResult> InsertPictureInfo(InsertPictureInfoCommand param)
        {
            return await _mediator.Send(param);
        }
 


    }
}
